#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <error.h>
#include <pthread.h>

#define BUFF_LEN 1024
#define PORT 1077

int conn_fd;
void process_client();
int find_byte_in_arr(char arr[], size_t search_begin, size_t search_length, char c);

/**
 * 接受adas设备码流并解析为pcm
 */
int main()
{
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(struct sockaddr_in)); //清零
    server_addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    server_addr.sin_port = htons(PORT);
    server_addr.sin_family = AF_INET;

    //绑定地址结构到套接字描述符
    if (bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("bind error\n");
        return -1;
    }

    if (listen(listen_fd, 20) < -1)
    {
        perror("listen error\n");
    }

    while (1)
    { //接受客户端连接
        socklen_t addrlen = sizeof(struct sockaddr);
        struct sockaddr_in clientaddr; //客户端地址结构

        conn_fd = accept(listen_fd, (struct sockaddr *)&clientaddr, &addrlen);

        if (conn_fd < 0)
        {
            perror("accept error");
            return -1;
        }
        printf("accept success\n");

        pthread_t pid;

        if (pthread_create(&pid, NULL, process_client, NULL) < 0)
        {
            printf("pthread create error\n");
        }
    }
    close(listen_fd);
}

int print_char_arr(char arr[])
{
    for (size_t i = 0; i < sizeof(arr); i++)
    {
        if (arr[i] == '\0')
        {
            printf("\n");
            break;
        }
        else
        {
            printf("%x", arr[i]);
        }
    }
}
// 从arr数组里面查找c，从search_begin开始查找search_length个char
int find_byte_in_arr(char arr[], size_t search_begin, size_t search_length, char c)
{
    if (search_begin == -1)
        search_begin = 0;
    for (size_t i = search_begin; i < search_begin + search_length; i++)
    {
        if (arr[i] == '\0')
        {
            //\0表示EOF，需要返回
            return -1;
        }
        if (arr[i] == c)
        {
            return i;
        }
    }
    return -1;
}

//数组copy，从src往dest复制len个char数据
int copy_byte_arr(char src[], char dest[], size_t src_index, size_t dest_index, size_t len)
{
    for (size_t i = 0; i < len; i++)
    {
        dest[dest_index + i] = src[src_index + i];
    }
}

void process_client()
{
    int client_socket_fd = conn_fd;
    int size = 0;
    //单次socket read的buff
    char buff[BUFF_LEN];
    //rtp包解出来之后的buff
    char rtp_buff[2048];
    char rtp_buff_flag;
    //从设备拿到的音视频buff
    char av_raw_buff[1024 * 1024];

    char rtp_packet[1024];

    int start_pos = -1;
    int end_pos = -1;
    while (1)
    {
        memset(buff, 0, BUFF_LEN);
        size = read(client_socket_fd, buff, BUFF_LEN);

        //先查找7e开头的字节，标记为starPos
        if (size > 0)
        {
            if (start_pos < 0)
            {
                start_pos = find_byte_in_arr(buff, 0, size, 0x7e);
            }
            if (start_pos >= 0)
            {
                end_pos = find_byte_in_arr(buff, start_pos + 1, size, 0x7e);
                if (end_pos >= 0)
                {
                    //we found head and tail, then put into rtp_packet,and pass to ffmpeg
                    if (rtp_buff_flag == 0)
                    {
                        copy_byte_arr(buff, rtp_packet, start_pos, 0, end_pos - start_pos + 1);
                    }
                    else
                    {
                        copy_byte_arr(rtp_buff, rtp_packet, 0, 0, sizeof(rtp_buff));
                        copy_byte_arr(buff, rtp_packet, start_pos, sizeof(rtp_buff), end_pos - start_pos + 1);
                    }
                }
                else
                {
                    //no tail, put to rtp_buff
                    copy_byte_arr(buff, rtp_packet, start_pos, 0, end_pos - start_pos + 1);
                    rtp_buff_flag = 1;
                }
            }

            //print data receive by tcp channel
            printf("fd is %d, data size:%d, got data: ", client_socket_fd, size);
            for (size_t i = 0; i < size; i++)
            {
                printf("%x", buff[i]);
            }
            printf("\n");
        }
        else if (size == 0)
        {
            printf("socket closed \n");
            close(client_socket_fd);
        }
    }
}